<template>
  <view class="container tn-safe-area-inset-bottom">
    <!-- 导航栏 -->
    <tn-nav-bar fixed alpha customBack>
      <view slot="back" class='tn-custom-nav-bar__back' @click="goBack">
        <text class='icon tn-icon-left-arrow'></text>
      </view>
      <view slot="right" class="header-actions">
        <text class="tn-icon-more" @click="showMoreOptions"></text>
        <text class="tn-icon-target" @click="goToMap"></text>
      </view>
    </tn-nav-bar>
    
    <!-- 顶部标题区域 -->
    <view class="header-section">
      <view class="page-title">创建组织</view>
      <view class="page-subtitle">请提交组织的信息并耐心等待审核!</view>
    </view>
    
    <!-- 主内容区 -->
    <view class="main-content">
      <scroll-view class="form-scroll" scroll-y>
        <!-- 组织名称 -->
        <view class="form-item">
          <view class="form-label">
            <text>组织名称</text>
            <text class="required">*</text>
          </view>
          <input 
            class="form-input" 
            type="text" 
            placeholder="请输入组织名称"
            v-model="formData.name"
            maxlength="50"
          />
        </view>
        
        <!-- 负责人 -->
        <view class="form-item">
          <view class="form-label">
            <text>负责人</text>
            <text class="required">*</text>
          </view>
          <input 
            class="form-input" 
            type="text" 
            placeholder="请输入负责人"
            v-model="formData.manager"
            maxlength="20"
          />
        </view>
        
        <!-- 联系电话 -->
        <view class="form-item">
          <view class="form-label">
            <text>联系电话</text>
            <text class="required">*</text>
          </view>
          <input 
            class="form-input" 
            type="number" 
            placeholder="请输入联系电话"
            v-model="formData.phone"
            maxlength="11"
          />
        </view>
        
        <!-- 地址 -->
        <view class="form-item">
          <view class="form-label">
            <text>地址</text>
            <text class="tn-icon-location location-icon" @click.stop="getCurrentLocation"></text>
          </view>
          <view class="address-container">
            <view class="map-container">
              <map 
                class="map-view"
                :latitude="formData.latitude"
                :longitude="formData.longitude"
                :markers="mapMarkers"
                :scale="15"
                :show-location="true"
                @tap="selectAddress"
              ></map>
              <view class="map-logo">
                <text class="map-logo-text">腾讯地图</text>
              </view>
              <view class="map-action-btn" @click.stop="getLocation">
                <text class="tn-icon-location"></text>
                <text>定位</text>
              </view>
            </view>
          </view>
          <view class="address-actions">
            <button class="address-btn" @click="getLocationWithPermission">获取当前位置</button>
            <button class="address-btn primary" @click="selectAddress">选择位置</button>
          </view>
          <view v-if="formData.address" class="address-text">{{ formData.address }}</view>
        </view>
        
        <!-- 公众号 -->
        <view class="form-item">
          <view class="form-label">
            <text>公众号</text>
          </view>
          <input 
            class="form-input" 
            type="text" 
            placeholder="请输入组织公众号"
            v-model="formData.wechatAccount"
            maxlength="50"
          />
        </view>
        
        <!-- 组织标签 -->
        <view class="form-item">
          <view class="form-label">
            <text>组织标签</text>
            <text class="required">*</text>
          </view>
          <view class="tags-container" @click="showTagSelector">
            <view v-if="formData.tags.length > 0" class="tags-list">
              <view 
                class="tag-item" 
                v-for="(tag, index) in formData.tags" 
                :key="index"
              >
                {{ tag }}
                <text class="tag-close" @click.stop="removeTag(index)">×</text>
              </view>
            </view>
            <view v-else class="tags-placeholder">请选择组织标签</view>
          </view>
        </view>
        
        <!-- 组织介绍 -->
        <view class="form-item">
          <view class="form-label">
            <text>组织介绍</text>
          </view>
          <textarea 
            class="form-textarea" 
            placeholder="请输入组织介绍"
            v-model="formData.introduction"
            maxlength="500"
            :auto-height="true"
          ></textarea>
          <view class="char-count">{{ formData.introduction.length }}/500</view>s
        </view>
        
        <!-- 轮播图 -->
        <view class="form-item">
          <view class="form-label">
            <text>轮播图</text>
            <text class="required">*</text>
          </view>
          <view class="upload-container">
            <view 
              class="upload-item" 
              v-for="(image, index) in formData.carouselImages" 
              :key="index"
            >
              <image :src="image" class="upload-image" mode="aspectFill"></image>
              <view class="image-delete" @click="removeImage(index)">
                <text class="tn-icon-close"></text>
              </view>
            </view>
            <view 
              class="upload-item upload-placeholder" 
              @click="chooseImage"
              v-if="formData.carouselImages.length < 9"
            >
              <text class="tn-icon-plus upload-icon"></text>
            </view>
          </view>
          <view class="upload-tip">最多上传9张图片</view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 确认按钮 -->
    <view class="submit-section">
      <button class="submit-btn" @click="handleSubmit" :disabled="!canSubmit">
        确认
      </button>
    </view>
    
    <!-- 底部占位 -->
    <view class='tn-tabbar-height'></view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        name: '',
        manager: '',
        phone: '',
        address: '',
        latitude: 43.8517, // 默认坐标（吉林市）
        longitude: 126.5547,
        wechatAccount: '',
        tags: [],
        introduction: '',
        carouselImages: []
      },
      
      // 地图标记
      mapMarkers: [],
      
      // 可选标签列表
      availableTags: [
        '校友总会', '地方分会', '院系分会', '行业校友',
        '兴趣爱好', '公益活动', '学术交流', '创业合作',
        '体育健身', '文化艺术', '志愿服务', '其他'
      ]
    }
  },
  
  computed: {
    // 检查是否可以提交
    canSubmit() {
      return this.formData.name.trim() &&
             this.formData.manager.trim() &&
             this.formData.phone.trim() &&
             this.formData.tags.length > 0 &&
             this.formData.carouselImages.length > 0;
    }
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.showModal({
        title: '提示',
        content: '确定要离开吗？未保存的内容将丢失',
        cancelText: '取消',
        confirmText: '确定',
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack({ delta: 1 });
          }
        }
      });
    },
    
    // 显示更多选项
    showMoreOptions() {
      uni.showActionSheet({
        itemList: ['保存草稿', '清空表单', '帮助'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.saveDraft();
          } else if (res.tapIndex === 1) {
            this.clearForm();
          } else if (res.tapIndex === 2) {
            this.showHelp();
          }
        }
      });
    },
    
    // 初始化地图
    initMap() {
      this.mapMarkers = [{
        id: 1,
        latitude: this.formData.latitude,
        longitude: this.formData.longitude,
        title: this.formData.address || '组织位置',
        iconPath: '/static/location.png',
        width: 30,
        height: 30
      }];
    },
    
    // 获取当前位置
    // 在页面的方法中调用（例如按钮点击事件）
	getLocationWithPermission(){
		uni.getLocation({
			type: 'gcj02', //返回可以用于uni.openLocation的经纬度
			success: function (res) {
				const latitude = res.latitude;
				const longitude = res.longitude;
				uni.openLocation({
					latitude: latitude,
					longitude: longitude,
					success: function () {
						console.log('success');
					}
				});
			}
		});
	},
   


    
    // 显示标签选择器
    showTagSelector() {
      uni.showActionSheet({
        itemList: this.availableTags,
        success: (res) => {
          const selectedTag = this.availableTags[res.tapIndex];
          if (!this.formData.tags.includes(selectedTag)) {
            this.formData.tags.push(selectedTag);
          } else {
            uni.showToast({
              title: '标签已存在',
              icon: 'none'
            });
          }
        }
      });
    },
    
    // 移除标签
    removeTag(index) {
      this.formData.tags.splice(index, 1);
    },
    
    // 选择图片
    chooseImage() {
      const remaining = 9 - this.formData.carouselImages.length;
      uni.chooseImage({
        count: remaining,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.formData.carouselImages = this.formData.carouselImages.concat(res.tempFilePaths);
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
        }
      });
    },
    
    // 移除图片
    removeImage(index) {
      this.formData.carouselImages.splice(index, 1);
    },
    
    // 提交表单
    handleSubmit() {
      // 表单验证
      if (!this.formData.name.trim()) {
        uni.showToast({
          title: '请输入组织名称',
          icon: 'none'
        });
        return;
      }
      
      if (!this.formData.manager.trim()) {
        uni.showToast({
          title: '请输入负责人',
          icon: 'none'
        });
        return;
      }
      
      if (!this.formData.phone.trim()) {
        uni.showToast({
          title: '请输入联系电话',
          icon: 'none'
        });
        return;
      }
      
      // 验证手机号格式
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!phoneReg.test(this.formData.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        });
        return;
      }
      
      if (this.formData.tags.length === 0) {
        uni.showToast({
          title: '请选择组织标签',
          icon: 'none'
        });
        return;
      }
      
      if (this.formData.carouselImages.length === 0) {
        uni.showToast({
          title: '请上传轮播图',
          icon: 'none'
        });
        return;
      }
      
      // 显示提交确认
      uni.showModal({
        title: '确认提交',
        content: '提交后将进入审核流程，请确认信息无误',
        cancelText: '取消',
        confirmText: '确认提交',
        success: (res) => {
          if (res.confirm) {
            this.submitForm();
          }
        }
      });
    },
    
    // 提交表单到服务器
    submitForm() {
      uni.showLoading({
        title: '提交中...',
        mask: true
      });
      
      // TODO: 这里应该调用实际的API接口
      // 模拟API调用
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 2000
        });
        
        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack({ delta: 1 });
        }, 2000);
      }, 1500);
    },
    
    // 保存草稿
    saveDraft() {
      try {
        uni.setStorageSync('orgDraft', this.formData);
        uni.showToast({
          title: '草稿已保存',
          icon: 'success'
        });
      } catch (e) {
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        });
      }
    },
    
    // 清空表单
    clearForm() {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有表单内容吗？',
        cancelText: '取消',
        confirmText: '确定',
        success: (res) => {
          if (res.confirm) {
            this.formData = {
              name: '',
              manager: '',
              phone: '',
              address: '',
              latitude: 43.8517,
              longitude: 126.5547,
              wechatAccount: '',
              tags: [],
              introduction: '',
              carouselImages: []
            };
            this.initMap();
            uni.showToast({
              title: '已清空',
              icon: 'success'
            });
          }
        }
      });
    },
    
    // 显示帮助
    showHelp() {
      uni.showModal({
        title: '帮助',
        content: '1. 带*号为必填项\n2. 组织标签至少选择一个\n3. 轮播图至少上传一张\n4. 提交后需要等待审核',
        showCancel: false,
        confirmText: '我知道了'
      });
    }
  },
  
  onLoad() {
    // 加载草稿
    try {
      const draft = uni.getStorageSync('orgDraft');
      if (draft) {
        uni.showModal({
          title: '发现草稿',
          content: '是否继续编辑上次保存的草稿？',
          cancelText: '不使用',
          confirmText: '使用',
          success: (res) => {
            if (res.confirm) {
              this.formData = draft;
              this.initMap();
            } else {
              // 不使用草稿时，尝试获取当前位置（不自动，让用户手动触发）
              this.initMap();
            }
          }
        });
      } else {
        // 没有草稿时，初始化地图，不自动获取位置（避免权限问题）
        this.initMap();
      }
    } catch (e) {
      console.error('加载草稿失败:', e);
      this.initMap();
    }
  }
}
</script>

<style lang="scss" scoped>
// 导航栏样式
.tn-custom-nav-bar__back {
  width: 60%;
  height: 100%;
  position: relative;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  box-sizing: border-box;
  background-color: rgba(0, 0, 0, 0.15);
  border-radius: 1000rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.5);
  color: #FFFFFF;
  font-size: 18px;
  
  .icon {
    display: block;
    flex: 1;
    margin: auto;
    text-align: center;
  }
}

.header-actions {
  display: flex;
  gap: 20rpx;
  padding-right: 20rpx;
  
  text {
    font-size: 36rpx;
    color: #FFFFFF;
    padding: 10rpx;
  }
}

// 主容器样式
.container {
  background-color: #f5f7fa;
  min-height: 100vh;
}

// 顶部标题区域
.header-section {
  background: linear-gradient(135deg, #2E86AB 0%, #1F4D4B 100%);
  padding: 120rpx 40rpx 60rpx;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: url('https://picsum.photos/800/400');
    background-size: cover;
    background-position: center;
    opacity: 0.2;
    filter: blur(10rpx);
  }
}

.page-title {
  font-size: 48rpx;
  font-weight: bold;
  color: #FFFFFF;
  margin-bottom: 16rpx;
  position: relative;
  z-index: 1;
}

.page-subtitle {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.9);
  position: relative;
  z-index: 1;
}

// 主内容区
.main-content {
  flex: 1;
  padding: 30rpx 20rpx;
}

.form-scroll {
  height: calc(100vh - 500rpx);
}

// 表单项样式
.form-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.form-label {
  display: flex;
  align-items: center;
  font-size: 30rpx;
  font-weight: 500;
  color: #1F4D4B;
  margin-bottom: 20rpx;
}

.required {
  color: #FF5722;
  margin-left: 4rpx;
}

.location-icon {
  margin-left: 12rpx;
  font-size: 32rpx;
  color: #2E86AB;
}

// 输入框样式
.form-input {
  width: 100%;
  height: 80rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #f5f7fa;
  border-radius: 12rpx;
  padding: 0 24rpx;
  box-sizing: border-box;
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #f5f7fa;
  border-radius: 12rpx;
  padding: 24rpx;
  box-sizing: border-box;
  line-height: 1.6;
}

.char-count {
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 12rpx;
}

// 地址地图样式
.address-container {
  margin-bottom: 16rpx;
}

.map-container {
  position: relative;
  width: 100%;
  height: 300rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.map-view {
  width: 100%;
  height: 100%;
}

.map-logo {
  position: absolute;
  bottom: 12rpx;
  right: 12rpx;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
}

.map-logo-text {
  font-size: 22rpx;
  color: #666;
}

.address-text {
  font-size: 26rpx;
  color: #666;
  padding: 12rpx 0;
  word-break: break-all;
}

.address-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 16rpx;
}

.address-btn {
  flex: 1;
  height: 64rpx;
  line-height: 64rpx;
  font-size: 26rpx;
  border-radius: 32rpx;
  background-color: #f5f7fa;
  color: #666;
  border: none;
  transition: all 0.2s ease;
  
  &:active {
    transform: scale(0.98);
    background-color: #eef2f5;
  }
  
  &.primary {
    background-color: #e8f3ff;
    color: #2E86AB;
    
    &:active {
      background-color: #d0e6ff;
    }
  }
}

.map-action-btn {
  position: absolute;
  top: 16rpx;
  right: 16rpx;
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 20rpx;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 30rpx;
  font-size: 24rpx;
  color: #2E86AB;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  z-index: 10;
  
  text:first-child {
    font-size: 28rpx;
  }
}

// 标签选择样式
.tags-container {
  min-height: 80rpx;
  background-color: #f5f7fa;
  border-radius: 12rpx;
  padding: 20rpx;
  box-sizing: border-box;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.tag-item {
  display: inline-flex;
  align-items: center;
  padding: 8rpx 20rpx;
  background-color: #e8f3ff;
  color: #2E86AB;
  border-radius: 30rpx;
  font-size: 26rpx;
}

.tag-close {
  margin-left: 8rpx;
  font-size: 32rpx;
  font-weight: bold;
  color: #2E86AB;
  line-height: 1;
}

.tags-placeholder {
  font-size: 28rpx;
  color: #999;
}

// 图片上传样式
.upload-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.upload-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.upload-image {
  width: 100%;
  height: 100%;
}

.upload-placeholder {
  background-color: #f5f7fa;
  border: 2rpx dashed #ddd;
  display: flex;
  justify-content: center;
  align-items: center;
}

.upload-icon {
  font-size: 60rpx;
  color: #999;
}

.image-delete {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  
  text {
    font-size: 24rpx;
    color: #fff;
  }
}

.upload-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 12rpx;
}

// 提交按钮区域
.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background-color: #fff;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  font-size: 32rpx;
  font-weight: 500;
  background: linear-gradient(135deg, #1F4D4B 0%, #2E86AB 100%);
  color: #fff;
  border-radius: 44rpx;
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(31, 77, 75, 0.3);
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 8rpx rgba(31, 77, 75, 0.3);
  }
  
  &[disabled] {
    background: #ccc;
    box-shadow: none;
  }
}

// 底部占位
.tn-tabbar-height {
  min-height: 120rpx;
  height: calc(140rpx + env(safe-area-inset-bottom));
}
</style>
s